/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.hcht.xrlh.zfdxktitle.web;

import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.hcht.xrlh.sx.entity.DrSx;
import com.hcht.xrlh.sx.service.DrSxService;
import com.hcht.xrlh.zfdxk.entity.DrZfdxk;
import com.hcht.xrlh.zfdxk.service.DrZfdxkService;
import com.hcht.xrlh.zfdxktitle.entity.DrZfdxkTitle;
import com.hcht.xrlh.zfdxktitle.service.DrZfdxkTitleService;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * 执法对象属性设置Controller
 * @author lrz
 * @version 2016-12-20
 */
@Controller
@RequestMapping(value = "${adminPath}/zfdxktitle/drZfdxkTitle")
public class DrZfdxkTitleController extends BaseController {

	@Autowired
	private DrZfdxkTitleService drZfdxkTitleService;
	
	@Autowired
	private DrZfdxkService drZfdxkService;
	
	@Autowired
	private DrSxService sxService;
	@ModelAttribute
	public DrZfdxkTitle get(@RequestParam(required=false) String id) {
		DrZfdxkTitle entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = drZfdxkTitleService.get(id);
		}
		if (entity == null){
			entity = new DrZfdxkTitle();
		}
		return entity;
	}
	
	@RequiresPermissions("zfdxktitle:drZfdxkTitle:view")
	@RequestMapping(value = {"list", ""})
	public String list(DrZfdxkTitle drZfdxkTitle, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<DrZfdxkTitle> page = drZfdxkTitleService.findPage(new Page<DrZfdxkTitle>(request, response), drZfdxkTitle); 
		model.addAttribute("page", page);
		return "xrlh/zfdxktitle/drZfdxkTitleList";
	}

	@RequiresPermissions("zfdxktitle:drZfdxkTitle:view")
	@RequestMapping(value = "form")
	public String form(DrSx drSx, Model model,HttpServletRequest request, HttpServletResponse response) {
		drSx = sxService.get(request.getParameter("id"));
		List<DrZfdxkTitle> list_t = Lists.newArrayList();
		DrZfdxkTitle title = new DrZfdxkTitle();
		title.setSxId(drSx.getId());
		list_t = drZfdxkTitleService.findList(title);
		drSx.setDrZfdxkTitleList(list_t);
		model.addAttribute("drSx", drSx);
		return "xrlh/zfdxktitle/drZfdxkTitleForm";
	}

	@RequiresPermissions("zfdxktitle:drZfdxkTitle:edit")
	@RequestMapping(value = "save")
	public String save(DrSx drSx, HttpServletRequest request, HttpServletResponse response,Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, drSx)){
			return form(drSx, model,request,response);
		}

		
		drZfdxkTitleService.save(drSx);
		addMessage(redirectAttributes, "执法对象属性设置成功");
		//return "redirect:"+Global.getAdminPath()+"/zfdxktitle/drZfdxkTitle/?repage";
		return "redirect:"+Global.getAdminPath()+"/zfdxk/drZfdxk/form?id="+drSx.getId();
	}
	
	@RequiresPermissions("zfdxktitle:drZfdxkTitle:edit")
	@RequestMapping(value = "delete")
	public String delete(DrZfdxkTitle drZfdxkTitle, RedirectAttributes redirectAttributes) {
		drZfdxkTitleService.delete(drZfdxkTitle);
		addMessage(redirectAttributes, "删除执法对象属性设置成功");
		return "redirect:"+Global.getAdminPath()+"/zfdxktitle/drZfdxkTitle/?repage";
	}

	/**
	 * 导入数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("zfdxktitle:drZfdxkTitle:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response) {
		String sxId = request.getParameter("sx_id");
		String delf = request.getParameter("delf");
		//删除原有表头		
		DrSx sx = sxService.get(sxId);
		List<DrZfdxkTitle> list_t = Lists.newArrayList();
		DrZfdxkTitle title = new DrZfdxkTitle();
		title.setSxId(sx.getId());
		list_t = drZfdxkTitleService.findList(title);
		if(list_t.size()>0){
			DrZfdxkTitle drZfdxkTitle = list_t.get(0);
			drZfdxkTitleService.deleteBySx(drZfdxkTitle);
		}
		List<DrZfdxkTitle> drZfdxkTitleList = Lists.newArrayList();
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			Row row= ei.getRow(0);
			int columns = 0;
			for(int i=0;i<100;i++){
				Object obj = ei.getCellValue(row, i);
				if(obj==null||obj.toString().equals("")){
					break;
				}
				DrZfdxkTitle t = new DrZfdxkTitle();
				t.setDelFlag("0");
				t.setDrSx(sx);
				t.setDxTMc(obj.toString());
				t.setDxTXh((long)(i+1));
				t.setId("");
				//t.preInsert();
				drZfdxkTitleList.add(t);
				columns++;

			}
			sx.setDrZfdxkTitleList(drZfdxkTitleList);
			drZfdxkTitleService.save(sx);
			
			//删除现有执法对象
			if("1".equals(delf)){
				DrZfdxk delPara = new DrZfdxk();
				delPara.setSxId(sxId);
				//drZfdxkService.deleteBySxId(delPara);
				drZfdxkService.deleteBySxId_1(delPara);
			}
			//int rows = ei.getDataRowNum();
			int rowsLast = ei.getLastDataRowNum();
			Class c = DrZfdxk.class;
			
			if(rowsLast>1){
				//插入执法对象库
				List<DrZfdxk> dx_list = Lists.newArrayList();
				for(int j=1;j<=rowsLast;j++){
					Row rowDx= ei.getRow(j);
					Object dx = c.newInstance();
					for(int k=0;k<20;k++){
						Object cellVal = ei.getCellValue(rowDx, k);
						if(cellVal!=null){
							Method m = c.getMethod("setCol"+(k+1), new Class[] {String.class});
							m.invoke(dx, new Object[]{cellVal.toString()});
						}
					}
					DrZfdxk dx_ = (DrZfdxk)dx;
					dx_.setDelFlag("0");
					dx_.setId("");
					dx_.setSxId(sxId);
					dx_list.add(dx_);
				}
				sx.setDrZfdxkList(dx_list);
				drZfdxkService.save(sx);
			}
/*			System.out.println("columns========="+columns);
			System.out.println("rows========="+rows);
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);*/
			addMessage(redirectAttributes, "执法对象属性设置成功");
			//return "redirect:"+Global.getAdminPath()+"/zfdxktitle/drZfdxkTitle/?repage";
			
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入执法对象数据失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/zfdxk/drZfdxk/form?id="+sx.getId();
    }
	
	@RequiresPermissions("zfdxktitle:drZfdxkTitle:edit")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(DrSx drSx, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String sxId = request.getParameter("sx_id");
		drSx = sxService.get(sxId); 
		try {
            String fileName = drSx.getSxMc()+"-"+DateUtils.getDate("yyyyMMdd")+".xlsx";
            DrZfdxkTitle drZfdxkTitle = new DrZfdxkTitle();
            drZfdxkTitle.setSxId(sxId);
            List<DrZfdxkTitle> title = drZfdxkTitleService.findList(drZfdxkTitle);
            String[] title_ = new String[title.size()];
            for(int i=0;i<title.size();i++){
            	title_[i] = title.get(i).getDxTMc();
            }
            DrZfdxk drZfdxk = new DrZfdxk();
            drZfdxk.setDrSx(drSx);
            List<DrZfdxk> list = drZfdxkService.findList(drZfdxk);
            
            ExportExcel ee = new ExportExcel("", title_,DrZfdxk.class,1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出执法对象库失败！失败信息："+e.getMessage());
		}
		//addMessage(redirectAttributes, "执法对象导出成功");
		redirectAttributes.addAttribute("id", sxId);
		return "redirect:"+Global.getAdminPath()+ "/zfdxktitle/drZfdxkTitle/form";
    }
}